<template>
<div class="containerWrap">
  <el-container class="container">
    <el-main class="rightMain">
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              角色名称：<el-input size="small" placeholder="请输入角色名称" v-model="queryData.roleName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button size="small" @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="tableMain">
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"
                     @givePrimise="givePrimise" />
        </el-main>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible"  :close-on-click-modal="false" :before-close="close" class="dialog_style">
          <div class="formWrapper">
            <el-form class="formMain" :model="formData"
                    :rules="rules"
                    ref="formData"
                    label-width="80px"
                    size="small">
              <el-divider content-position="left">基本信息</el-divider>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="角色名：" prop="name">
                    <el-input v-model="formData.roleName" placeholder="角色名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排序：" prop="name">
                    <el-input v-model="formData.displayOrder" placeholder="排序"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button size="small" @click="cancel('formData')">取 消</el-button>
              <el-button size="small" type="primary" :disabled="showOnly" @click="save('formData')">提 交</el-button>
            </div>
          </div>
        </el-dialog>
        <el-dialog title="角色权限" :visible.sync="dialogFormPromise" :before-close="closePromise" class="dialog_style role-dialog">
          <el-tree :default-expand-all="expandStatus"
            :show-checkbox="true"
            ref="tree"
            node-key="id"
            :data="permissionTree"
            :props="defaultProps"
            :default-checked-keys="curPermissionIds"
            :render-after-expand="false"
            :highlight-current="true"
            :check-strictly="true"
            @check="clickDeal">
          </el-tree>
          <div slot="footer" id="permission" class="dialog-footer">
            <el-button @click="closePromise('formData')">取 消</el-button>
            <el-button type="primary" @click="savePermission" >提 交</el-button>
          </div>
        </el-dialog>
      </el-container>
    </el-main>
  </el-container>
</div>
</template>
<script>
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import PTree from '@/components/PromiseTree'
import { createRole, findRole, updateRole, deleteRole, createRolePermission, findPermissionIdsByRoleId } from '@/http/setApi'
import { getAllPermission } from '@/http/AppApi'
export default {
  data () {
    return {
      active: 1,
      mapMode: 'full',
      dialogTitle: '新增角色',
      currentSelectedRowId: '',
      showMap: false,
      showOnly: false,
      expandStatus: false,
      dialogFormPromise: false,
      dialogFormVisible: false,
      treeData: [],
      permissionTree: [],
      curPermissionIds: [],
      currentSelectedData: [],
      formData: {},
      pageData: {},
      queryData: {},
      mapTarget: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableColumns: [
        { label: '名称', prop: 'roleName' },
        { label: '排序', prop: 'displayOrder' },
        { label: '更新时间', prop: 'updateTime', formatter: this.timeFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        roleName: [{
          required: true,
          message: '填写角色名',
          trigger: 'blur'
        }]
      }
    }
  },
  mounted () {
    this.getTableData()
    this.getAllPermission()
  },
  components: {BtnGroup, AppTable, PTree},
  methods: {
    timeFormatter (row) {
      if (row && row.updateTime) {
        return this.$moment(row.updateTime).format('YYYY-MM-DD')
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.beforeSubmit()
          if (this.formData.id) {
            updateRole(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.cancel(formName)
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          } else {
            createRole(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.cancel(formName)
                this.dialogFormVisible = false
                this.$refs[formName].resetFields()
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          }
        }
      })
    },
    beforeSubmit () {
      console.log(this.formData.allIdArr)
      if (this.formData.allIdArr && this.formData.allIdArr.length > 0) {
        console.log(1111)
        let allId = this.formData.allIdArr.join(',')
        this.$set(this.formData, 'allId', allId)
        let unitId = this.formData.allIdArr[this.formData.allIdArr.length - 1]
        this.$set(this.formData, 'unitId', unitId)
      }
      return true
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteRole(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({type: 'success', message: '删除成功'})
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    savePermission () {
      let arr = this.$refs['tree'].getCheckedNodes(false, true)
      if (arr.length <= 0) return ''
      let CheckedKeys = []
      for (let i = 0; i < arr.length; i++) {
        CheckedKeys.push(arr[i].id)
      }
      let data = {}
      data.roleId = this.curRole.id
      data.permissionIdList = CheckedKeys
      createRolePermission(data).then(resp => {
        if (resp && resp.code === '200') {
          this.getTableData()
          this.$message({message: '保存成功', type: 'success'})
        }
      })
    },
    getTableData () {
      let param = this.queryData
      findRole(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            this.$set(this.pageData, 'isRole', true)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getAllPermission () {
      getAllPermission().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.permissionTree = data
        }
      })
    },
    btnClickCallback (callbackData) {
      this.dialogFormVisible = true
      this.showOnly = callbackData.showOnly
      this.dialogTitle = callbackData.dialogTitle
      if (callbackData.btnType === 'post') {
        this.formData = {}
      } else if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        // let data = callbackData.rows[0]

      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
      }
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    close (type) {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    givePrimise (row) {
      this.dialogFormPromise = true
      this.curRole = row.rows[0]
      this.curPermissionIds = []
      this.dialogTitle = row.roleName + '-权限配置'
      this.curPermissionIds = []
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([])
      }
      findPermissionIdsByRoleId(row.rows[0]).then(resp => {
        if (resp && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            this.curPermissionIds = data
          }
        }
      })
    },
    // 树形菜单复选框点击事件
    clickDeal (currentObj, treeStatus) {
      // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
      // -1未选中
      let selected = treeStatus.checkedKeys.indexOf(currentObj.id)

      // 选中
      if (selected !== -1) {
        // 子节点只要被选中父节点就被选中
        this.selectedParent(currentObj)
        // 统一处理子节点为相同的勾选状态
        this.uniteChildSame(currentObj, true)
        // 未选中
      } else {
        // 取消子节点的选中状态触发
        if (currentObj.parentId !== -1) {
          this.removeParent(currentObj)
        }
        // 点击父节点未选中子节点全部取消选中,子节点全部未选中父节点取消选中
        if (currentObj.children && currentObj.children.length !== 0) {
          this.uniteChildSame(currentObj, false)
        }
      }
    },
    //  统一处理子节点为相同的勾选状态
    uniteChildSame (treeList, isSelected) {
      if (treeList.children === null) {
      } else {
        // this.$refs.tree.setChecked(treeList.id, isSelected)
        for (let i = 0; i < treeList.children.length; i++) {
          // this.uniteChildSame(treeList.children[i], isSelected)
          this.$refs.tree.setChecked(treeList.children[i], isSelected)
        }
      }
    },
    // 统一处理父节点为选中
    selectedParent (currentObj) {
      let currentNode = this.$refs.tree.getNode(currentObj)
      if (currentNode.parent.key !== undefined) {
        this.$refs.tree.setChecked(currentNode.parent, true)
        this.selectedParent(currentNode.parent)
      }
    },
    //  子节点全没选中就取消父级的选中
    removeParent (currentObj) {
      let a = 0
      let b = 0
      let currentNode = this.$refs.tree.getNode(currentObj)
      if (currentNode.parent !== null) {
        if (currentNode.parent.key !== undefined) {
          // 根节点
          this.$refs.tree.setChecked(currentNode.parent, true)
          // 递归判断子节点
          this.removeParent(currentNode.parent)
        }
      }
      // 不为0表示为父节点
      if (currentNode.childNodes.length !== 0) {
        // 循环判断父节点下的子节点
        for (let i = 0; i < currentNode.childNodes.length; i++) {
          // 判断父节点下的子节点是否全为false
          if (currentNode.childNodes[i].checked === false) {
            ++a
            // a === currentNode.childNodes.length 表明子节点全为false
            if (a === currentNode.childNodes.length) {
              // 等于 undefined 跳过,不等于继续执行
              if (currentNode.childNodes[i].parent.key !== undefined) {
                // 父元素设置为false
                this.$refs.tree.setChecked(currentNode.childNodes[i].parent, false)
                // 循环上级父节点下的子节点
                for (let i = 0; i < currentNode.parent.childNodes.length; i++) {
                  // 判断父节点下的子节点是否全为false
                  if (currentNode.parent.childNodes[i].checked === false) {
                    ++b
                    // b === currentNode.parent.childNodes.length 表明子节点全为false
                    if (b === currentNode.parent.childNodes.length) {
                      // 父元素设置为false
                      this.$refs.tree.setChecked(currentNode.parent.key, false)
                      // 继续递归循环判断
                      this.removeParent(currentNode.parent)
                      // console.log(currentNode.parent)
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    closePromise () {
      this.dialogFormPromise = false
    }
  }
}
</script>
<style scoped>
  .containerWrap {
    padding:10px;
    height: 100%;
    box-sizing: border-box
  }
  .container {
    height: 100%;
  }
   .role-dialog .el-dialog{
     min-height: 500px
   }
  .role-dialog >>> .el-dialog {
    width:40%
  }
</style>
